package com.ruoyi.wms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.wms.entity.WmsProductInfo;
import com.ruoyi.wms.entity.WmsProductTypeInfo;
import com.ruoyi.wms.entity.WmsWarehouseLocationInfo;
import com.ruoyi.wms.mapper.WmsProductInfoMapper;
import com.ruoyi.wms.service.IWmsProductInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.wms.service.IWmsProductTypeInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author 张晓光
 * @since 2023-10-26
 */
@Slf4j
@Service
@AllArgsConstructor
public class WmsProductInfoServiceImpl extends ServiceImpl<WmsProductInfoMapper, WmsProductInfo> implements IWmsProductInfoService {

    private final IWmsProductTypeInfoService iWmsProductTypeInfoService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importProduct(List<WmsProductInfo> wmsProductInfos, boolean updateSupport) {
        StringBuffer sb = new StringBuffer();
        int insertSuccess = 0;
        int fail = 0;
        int updateSuccess = 0;
        List<WmsProductTypeInfo> list = iWmsProductTypeInfoService.list();
        Map<String,WmsProductTypeInfo> typeMap = list.stream().collect(Collectors.toMap(WmsProductTypeInfo::getTypeCode,(item)->item));
        for(WmsProductInfo info : wmsProductInfos){
            WmsProductTypeInfo typeInfo = typeMap.get(info.getProductType());
            if(BeanUtil.isEmpty(typeInfo)){
                fail++;
                continue;
            }
            WmsProductInfo old = getByCode(info.getProductCode());
            info.setProductType(typeInfo.getId());
            if(old!=null && updateSupport){
                updateSuccess ++;
                info.setId(old.getId());
                updateById(info);
            }else{
                save(info);
                insertSuccess ++;
            }
        }
        sb.append("新增数据：").append(insertSuccess).append(",更新成功：").append(updateSuccess).append(",失败（类型错误）:").append(fail);
        return sb.toString();
    }

    @Override
    public WmsProductInfo getByCode(String productCode) {
        return getOne(Wrappers.<WmsProductInfo>lambdaQuery().eq(WmsProductInfo::getProductCode,productCode).last("limit 1"));
    }
}
